<script setup lang="ts">
import ComponentsWord from '@/components/ComponentsWord.vue';
// import ComponentsWord from '@/components/ComponentsEasyWord.vue';
import { onMounted, onUnmounted, onBeforeMount, ref, type Ref } from "vue";
import type { SSEChatParams } from "../assets/utils/sse";
import { sseService } from "../assets/utils/sse";
import { setUrlParams } from "@/service/sseUrl";
import { useCounterStore } from './../stores/counter'
import { storeToRefs } from 'pinia';

let appId = 'E68891E79A84E695B0E68DAEE58C85' // 默认应用缩写（我的数据包
let appName: string = '我的数据包' // 默认应用名（我的数据包）
let mode = 'create'
let editFileId: string | undefined
let editFileName: string | undefined
let pathUrl: string | undefined = appId

let currentApp: {
    名称: string
    缩写: string
    路由?: string
    图标?: string
    类型?: string
}

onBeforeMount(() => {
    const counterStore = useCounterStore()
    const { openFileInfo } = storeToRefs(counterStore)
    const currentFile = openFileInfo.value
    console.log('当前文件参数信息', currentFile)
    if (currentFile && currentFile.appId && currentFile.appName) {
        appId = currentFile.appId
        appName = currentFile.appName
        mode = 'update'
        currentApp = {
              缩写: currentFile.appId,
              名称: currentFile.appName,
          }
        editFileName = currentFile.fileName
        editFileId = currentFile.fileId
        pathUrl = currentFile.pathUrl
    }
    openFileInfo.value = {}

    if (!currentApp) {
          currentApp = {
              名称: appName,
              缩写: appId,
          }
      }
      console.log('当前应用', currentApp, mode)
})

let fileData: Ref<Object | undefined> = ref(undefined)

//see 链接
const sseServiceOpen = () => {
  console.log("尝试建立文件数据sse连接", pathUrl)
  const onopen = () => {
    console.log("建立文件数据sse连接成功", pathUrl)
  }
  const fileName = editFileId || 'readme'
  // 建立连接
  let sseChatParams: SSEChatParams = {
    onopen,
    url: setUrlParams(pathUrl, fileName),
    onmessage: (event: MessageEvent) => {
      // 收到消息
      console.log('文件数据：', event.data);
      if (event.data) {
        if (fileName === 'readme') { // 处理模板数据
          const dataObj = JSON.parse(event.data)
          console.log('模版数据', dataObj['模版数据']);
          fileData.value = dataObj['模版数据']
        } else {
          const dataObj = JSON.parse(event.data)
          console.log('模版数据', dataObj);
          // fileData.value = dataObj['内容'].main
          fileData.value = dataObj['内容']
        }
      }
    },
    finallyHandler: () => {
      console.log("finallyHandler操作")
    }
  };
  sseService.connect(sseChatParams)
}

onMounted(() => {
    if (mode === 'update') {
        sseServiceOpen()
    }
});
onUnmounted(() => {
    if (mode === 'update') {
        sseService.disconnect()
    }
})
</script>
<template>
  <ComponentsWord :fileData :mode :currentApp :editFileName />
</template>
<style scoped></style>